<template>
  <el-row>
    <div class="col-3 p-0">
      <el-drawer size="650px" title="我是标题" direction="ltr" v-model="listshow" :with-header="false" append-to-body>
        <Questionlist v-show="listshow" v-bind="{
        questions: questionlist,
        questionbankid,
        getquestioncount: getquestioncount,
        change: changePage,
        limit: limit, offset: offset
      }"></Questionlist>
      </el-drawer>

      <el-button class="btn-11" @click.stop="listshow = !listshow">
        <svg class="icon" aria-hidden="true">
          <use xlink:href="#icon-Menu" />
        </svg>
        &nbsp; 题单题目
      </el-button>
    </div>
    <div v-if="showChgPageBtn" class="col text-right">
      <el-button class="btn-11" @click="goNext(true)" :disabled="des === 'T' || questionlist.length == 1">
        <el-icon>
          <ArrowLeft />
        </el-icon>上一题
      </el-button>
      <span>
        &nbsp; {{ questionlist.findIndex((v) => v.ID == ID) + 1 }} /
        {{ questionlist.length }} &nbsp;({{ page }}页) &nbsp;
      </span>
      <el-button class="btn-11" :disabled="des === 'F' || questionlist.length == 1" @click="goNext(false)">
        下一题
        <el-icon>
          <ArrowRight />
        </el-icon>
      </el-button>
    </div>
  </el-row>
</template>

<script setup lang="ts">
import { ArrowLeft, ArrowRight } from '@element-plus/icons-vue';
import { computed, ref } from "vue";
import { useRoute, useRouter } from "vue-router";
import { useStore } from "vuex";
import { Iobj } from '../../../api';
import { Storekey } from "../../../interface";
import Studycodemodel from "../../../mysql_interface/studycodemodel";
import { delay } from '../../../util/time';
import Questionlist from "./questionlist.vue";

const router = useRouter();
const route = useRoute();
const store = useStore(Storekey);

const p = defineProps<{ ID?: number, index?: number, questionlist: Studycodemodel.Iquestion[] }>()
const ID = computed(() => {
  return p.ID;
});
const questionlist = computed(() => {
  return p.questionlist
});

const listshow = ref(false);
// routeQuery
const routeQuery = computed<{
  order: string, offset: number, limit: number,
  questionbankid?: number, userId?: number, teamid?: string[]
}>(() => {
  return route.query as any;
});
const questionbankid = computed(() => {
  return routeQuery.value.questionbankid;
});
const userId = computed(() => {
  return routeQuery.value.userId;
});
const order = computed(() => {
  return (routeQuery.value.order || "ID") as keyof Studycodemodel.Iquestion
});
const teamid = computed(() => {
  return routeQuery.value.teamid
})

const getquestioncount = computed<number>(() => {
  // 专题是单独获取的题目列表
  if (questionbankid.value || userId.value) {
    return questionlist.value.length
  }
  // 题库、比赛、任务
  return store.getters.getquestioncount;
});

const showChgPageBtn = computed(() => {
  return !!(route.query.jobid || route.query.activityid || questionbankid.value)
})

const des = computed<false | "T" | "F">(() => {
  const currQuestionIdx = questionlist.value.findIndex((v) => v?.ID == ID.value);
  // 上一题不可点击
  if (currQuestionIdx === 0 && offset.value == 0) {
    return "T";
  }
  // 下一题不可点击（仅在列表已全部加载时禁用）
  if (currQuestionIdx === questionlist.value.length - 1 && offset.value + limit.value >= getquestioncount.value) {
    return "F";
  }
  return false;
});

// 题目列表 分页用
// 题目列表 分页用
const page = computed(() => {
  return Math.floor(offset.value / limit.value) + 1;
});

const offset = computed<number>({
  get() {
    return Number(routeQuery.value.offset) || 0;
  },
  set(v) {
    if (v !== routeQuery.value.offset) {
      router.push({ query: { ...route.query, offset: v, showFirst: true }, });
    }
  },
});
const limit = computed<number>({
  get() {
    let defaultLimit = 20
    if (questionbankid.value || userId.value) {
      defaultLimit = questionlist.value.length
    }
    return Number(routeQuery.value.limit) || defaultLimit;
  },
  set(v) {
    if (v !== routeQuery.value.limit) {
      router.push({
        query: { ...routeQuery.value, limit: v, },
      });
    }
  },
});

function changePage(r: number) {
  offset.value = (r - 1) * limit.value;

}
// 下一题false、上一题true
async function goNext(isPrev: boolean) {
  const currQuestionIdx = questionlist.value.findIndex((v) => v?.ID == ID.value);
  let newId: number | undefined;
  let pageChangeOffset = 0;
  let shouldLoadQuestions = false;  // 新增变量用于判断是否需要加载新题目

  if (!isPrev && currQuestionIdx === questionlist.value.length - 1) {
    // 需要翻页到下一页
    shouldLoadQuestions = true;
    pageChangeOffset = limit.value;
  } else if (isPrev && currQuestionIdx === 0) {
    // 需要翻页到上一页
    shouldLoadQuestions = true;
    pageChangeOffset = -limit.value;
  }

  if (shouldLoadQuestions) {
    await loadQuestions(offset.value + pageChangeOffset);  // 加载新的一页题目
    await delay(30);  // 等待数据加载完成

    newId = isPrev ? questionlist.value[limit.value - 1]?.ID : questionlist.value[0]?.ID; // 设置新题目ID
  } else {
    // 如果不需要翻页，则直接设置新的题目ID
    newId = isPrev ? questionlist.value[currQuestionIdx - 1]?.ID : questionlist.value[currQuestionIdx + 1]?.ID;
  }

  if (newId) {
    const query = { ...route.query, showFirst: undefined };
    if (pageChangeOffset !== 0) {
      query.offset = offset.value + pageChangeOffset;
    }
    router.push({ params: { ID: newId }, query });  // 更新路由参数
  }
}

async function loadQuestions(newOffset: number) {
  const obj: Iobj<Studycodemodel.Iquestion> = {
    _offset: newOffset,
    _limit: limit.value, _order: order.value,
  };

  if (teamid.value && Array.isArray(teamid.value)) {
    obj.teamid = store.state.team?.rows.filter(e => teamid.value.includes(String(e.ID || ''))).map(e => e.ID);
  }
  if (route.query.ID) {
    obj.ID = route.query.ID;
  }
  if (route.query.name) {
    obj._like = ["name", route.query.name];
    const id = Number(route.query.name);
    if (id == Number(route.query.name)) {
      obj._like = ["ID", id];
    }
  }
  if (route.query.range) {
    obj.range = route.query.range;
  } else {
    obj.range = 'public';
  }
  if (route.query.jobid) {
    (obj as any).jobid = route.query.jobid;
  }
  if (route.query.activityid) {
    (obj as any).activityid = route.query.activityid;
  }

  // 专题、最近练习是单独接口获取题目列表
  if (!questionbankid.value || !userId.value) {
    await store.dispatch("actionquestion", obj);
  }
}



</script>
